package com.yunchang.spring.visitor.core.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;

/**
 * Created by jasontujun on 2019/9/17.
 */
public abstract class StreamUtil {

    private static final Logger logger = LoggerFactory.getLogger(StreamUtil.class);

    /**
     * 将输入流转换为String(utf-8编码)
     *
     * @param inputStream 输入流
     * @return 返回输入流的String形式内容。
     */
    public static String copyToString(InputStream inputStream) {
        return copyToString(inputStream, "utf-8");
    }

    /**
     * 将输入流转换为String
     *
     * @param inputStream 输入流
     * @param charsetName 字符集
     * @return 返回输入流的String形式内容。
     */
    public static String copyToString(InputStream inputStream, String charsetName) {
        if (inputStream == null) {
            return null;
        }
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
            byte[] buffer = new byte[1024];
            int read;
            while ((read = inputStream.read(buffer)) > 0) {
                baos.write(buffer, 0, read);
            }
            return new String(baos.toByteArray(), charsetName);
        } catch (Exception e) {
            logger.error("", e);
            return null;
        }
    }
}
